/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.nacos.naming.core.v2.service.impl;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.client.Client;
import com.alibaba.nacos.naming.core.v2.client.manager.ClientManager;
import com.alibaba.nacos.naming.core.v2.client.manager.ClientManagerDelegate;
import com.alibaba.nacos.naming.core.v2.event.client.ClientOperationEvent;
import com.alibaba.nacos.naming.core.v2.event.metadata.MetadataEvent;
import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.service.ClientOperationService;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.pojo.Subscriber;
import org.springframework.stereotype.Component;

/**
 * Operation service for ephemeral clients and services.
 *
 * @author xiweng.yy
 */
@Component("ephemeralClientOperationService")
public class EphemeralClientOperationServiceImpl implements ClientOperationService {
    
    private final ClientManager clientManager;
    
    public EphemeralClientOperationServiceImpl(ClientManagerDelegate clientManager) {
        this.clientManager = clientManager;
    }

    /**
     * 注册客户端实例
     * @param service  service
     * @param instance instance
     * @param clientId id of client
     */
    @Override
    public void registerInstance(Service service, Instance instance, String clientId) {
        /**
         * 将 Service 缓存进注册表 singletonRepository 中，若注册表中包含该 Service，则不做任何操作
         * 将 Namespace 作为 key，Set<Service> 作为 value，缓存进 namespaceSingletonMaps 中
         * 将 Service 缓存进一个 ConcurrentHashSet 集合中，
         * 然后再以 Service 的 NameSpace 作为 key，ConcurrentHashSet 集合作为 value 值，缓存进 namespaceSingletonMaps 中
         * 最后返回 Service
         */
        Service singleton = ServiceManager.getInstance().getSingleton(service);
        if (!singleton.isEphemeral()) {
            // 对持久实例抛出异常
            throw new NacosRuntimeException(NacosException.INVALID_PARAM,
                    String.format("Current service %s is persistent service, can't register ephemeral instance.",
                            singleton.getGroupedServiceName()));
        }

        /**
         * 根据客户端的 connectionId 获取 Client 对象（gRPC 底层封装的客户端对象）
         * clientId → ConnectionId
         * ☆☆☆☆☆
         */
        Client client = clientManager.getClient(clientId);
        if (!clientIsLegal(client, clientId)) {
            return;
        }

        /**
         * 将客户端传过来的实例对象，转成服务端对象
         * Instance：客户端实例对象
         * InstancePublishInfo：服务端实例对象，主要包装了 Instance，即主要封装了 ip 和 port。
         */
        InstancePublishInfo instanceInfo = getPublishInfo(instance);

        /**
         * service 与 Instance 关系绑定
         * ConcurrentHashMap<Service, InstancePublishInfo> publishers：
         * key 为 Service，
         * value 为 Instance 的包装对象，主要信息是 Instance 的 ip 和 port
         *
         * singleton：Service
         * instanceInfo：服务端实例对象(Instance 的包装对象)，主要信息是 Instance 的 ip 和 port
         *
         * 关系绑定完成后，服务端会发布一个客户端变更的异步处理事件(ClientChangedEvent)
         */
        client.addServiceInstance(singleton, instanceInfo);

        // 刷新客户端更新时间
        client.setLastUpdatedTime();

        // 发布客户端注册事件(ClientRegisterServiceEvent)
        NotifyCenter.publishEvent(new ClientOperationEvent.ClientRegisterServiceEvent(singleton, clientId));

        // 发布实例元数据变更事件(InstanceMetadataEvent)
        NotifyCenter
                .publishEvent(new MetadataEvent.InstanceMetadataEvent(singleton, instanceInfo.getMetadataId(), false));
    }
    
    @Override
    public void deregisterInstance(Service service, Instance instance, String clientId) {
        if (!ServiceManager.getInstance().containSingleton(service)) {
            Loggers.SRV_LOG.warn("remove instance from non-exist service: {}", service);
            return;
        }
        Service singleton = ServiceManager.getInstance().getSingleton(service);
        Client client = clientManager.getClient(clientId);
        if (!clientIsLegal(client, clientId)) {
            return;
        }
        InstancePublishInfo removedInstance = client.removeServiceInstance(singleton);
        client.setLastUpdatedTime();
        if (null != removedInstance) {
            NotifyCenter.publishEvent(new ClientOperationEvent.ClientDeregisterServiceEvent(singleton, clientId));
            NotifyCenter.publishEvent(
                    new MetadataEvent.InstanceMetadataEvent(singleton, removedInstance.getMetadataId(), true));
        }
    }
    
    @Override
    public void subscribeService(Service service, Subscriber subscriber, String clientId) {
        Service singleton = ServiceManager.getInstance().getSingletonIfExist(service).orElse(service);

        // 订阅者的客户端 clientId，即 ConnectionId
        Client client = clientManager.getClient(clientId);
        if (!clientIsLegal(client, clientId)) {
            return;
        }

        /**
         * 绑定订阅者和其订阅的目标服务，即给目标服务添加一个订阅者
         * singleton：订阅的目标服务
         * subscriber：订阅者
         */
        client.addServiceSubscriber(singleton, subscriber);
        // 刷新客户端更新时间
        client.setLastUpdatedTime();

        /**
         * 发布客户端订阅事件
         * singleton：目标服务
         * clientId：目标服务的订阅者
         */
        NotifyCenter.publishEvent(new ClientOperationEvent.ClientSubscribeServiceEvent(singleton, clientId));
    }
    
    @Override
    public void unsubscribeService(Service service, Subscriber subscriber, String clientId) {
        Service singleton = ServiceManager.getInstance().getSingletonIfExist(service).orElse(service);
        Client client = clientManager.getClient(clientId);
        if (!clientIsLegal(client, clientId)) {
            return;
        }
        client.removeServiceSubscriber(singleton);
        client.setLastUpdatedTime();
        // 发布客户端取消订阅事件
        NotifyCenter.publishEvent(new ClientOperationEvent.ClientUnsubscribeServiceEvent(singleton, clientId));
    }
    
    private boolean clientIsLegal(Client client, String clientId) {
        if (client == null) {
            Loggers.SRV_LOG.warn("Client connection {} already disconnect", clientId);
            return false;
        }
        if (!client.isEphemeral()) {
            Loggers.SRV_LOG.warn("Client connection {} type is not ephemeral", clientId);
            return false;
        }
        return true;
    }
}
